package task

import (
	"github.com/nsqio/go-nsq"
	"log"
	"strconv"
	"strings"
)

/**
 * 处理专家的分类
 */
func DealCateMsg(msg *nsq.Message) error {
	ids := strings.Split(string(msg.Body), "_")
	expertId, _ := strconv.Atoi(ids[0])
	uid, _ := strconv.Atoi(ids[1])
	return DealCate(expertId, uid)

}

func DealCate(expertId, uid int) error {
	products := make([]Product, 0)

	err := engine.Where("uid=?", uid).Find(&products)
	if err != nil {
		return err
	}
	pids := []int64{}
	for _, product := range products {
		pids = append(pids, product.Id)
	}

	cates := make([]ProductCategory, 0)
	err = engine.In("product_id", pids).Find(&cates)
	if err != nil {
		return err
	}
	cateDoctors := []CateDoctor{}
	var affected int64
	if len(cates) > 0 {
		engine.Where("doctor_id=?", expertId).Delete(new(CateDoctor))

		exists := make(map[string]bool)
		for _, cate := range cates {
			key := "" + strconv.Itoa(cate.CategoryId1) + "-" + strconv.Itoa(cate.CategoryId2)
			if _, ok := exists[key]; ok {
				continue
			}
			exists[key] = true
			cateDoctor := CateDoctor{
				DoctorId:    expertId,
				CategoryId1: cate.CategoryId1,
				CategoryId2: cate.CategoryId2,
			}

			cateDoctors = append(cateDoctors, cateDoctor)
		}

		affected, err = engine.Insert(&cateDoctors)
		if err != nil {
			return err
		}
	}

	log.Printf("hello test %v,%v,%v", expertId, uid, affected)
	return nil
}
